package com.lee.www.pictureframe;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;

public class Demo {

    public static void main(String[] args) {
        try {
            String videoPath = "E:\\temp\\VID_20230615_110359.mp4";
            getVideoPicture(videoPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取视频帧
     *
     * @param videoPath 视频地址
     */
    public static void getVideoPicture(String videoPath) throws Exception {
        File videoFile = new File(videoPath);
        if (!videoFile.exists()) {
            System.out.println("视频不存在：{}" + videoFile);
            return;
        }

        System.out.println("视频存在：{}" + videoFile);
        //实例化“截取视频”对象
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
        ff.start();
        int ftp = ff.getLengthInFrames();
        int flag = 0;
        Frame frame = null;
        while (flag <= ftp) {
            //获取帧
            frame = ff.grabImage();
            if (frame == null) {
                break;
            }
            flag++;
            File file = new File("E:\\temp\\VID_20230615_110359\\" + flag + ".jpg");
            System.err.println(file.getName());
            ImageIO.write(frameToBufferedImage(frame), "jpg", file);
        }
        ff.close();
        ff.stop();
    }

    /**
     * 帧转为流
     */
    private static RenderedImage frameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }
}
